package com.gengdan.service.impl;

import com.gengdan.bean.UserInfoBean;
import com.gengdan.bean.UserLoginBean;
import com.gengdan.dao.UserInfoDao;
import com.gengdan.service.EmailRelatedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;

@Service
public class EmailRelatedServiceImpl implements EmailRelatedService {

    @Autowired
    UserInfoDao userInfoDao;
    @Autowired
    HashMap<String,Object> hm;
    @Autowired
    HashMap<String,Object> reportHm;

    @Override
    public List<UserInfoBean> getUserInfoByUserId(int userId) {
        return userInfoDao.getUserInfoByUserId(userId);
    }

    @Override
    public HashMap buildAddress(UserLoginBean userLoginBean) {

        int userId = userLoginBean.getUserId();
        List<UserInfoBean> userInfoBeanList = getUserInfoByUserId(userId);
        UserInfoBean userInfoBean = userInfoBeanList.get(0);

        //30分钟后过期
        Date createTime = new Date(System.currentTimeMillis());
        Date outTime = new Date(System.currentTimeMillis()+30*60*1000);

        //忽略毫秒数
        //注释原因：不一定要忽略
        //long outdate = timestamp.getTime();

        //获取邮箱
        String email = userInfoBean.getUserEmail();
        //构造密匙
        String token = buildToken();
        //获取登录名
        String loginName = userLoginBean.getLoginName();

        userInfoBean.setOutTime(outTime);
        userInfoBean.setToken(token);
        userInfoBean.setCreateTime(createTime);
        userInfoBean.setStatus(0);

        userInfoDao.updateTokenInfo(userInfoBean);

        //基础地址
        String basePath = "http://111.205.28.204:8080/login/to_reset";
        String content = "?login_name="+loginName+"&token="+token;
        String path = basePath+content;

        reportHm.put("path",path);
        reportHm.put("email",email);

        return reportHm;
    }

    @Override
    public void emailSend(UserLoginBean userLoginBean) {
        HashMap h = buildAddress(userLoginBean);

        String path = h.get("path").toString();
        // 服务器地址:
        String smtp = "smtp.qq.com";
        // 登录用户名:
        final String username = "1318523317@qq.com";
        // 登录口令:
        final String password = "xmldgjotfanfjffj";
        // 连接到SMTP服务器587端口:
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp); // SMTP主机名
        props.put("mail.smtp.port", "587"); // 主机端口号
        props.put("mail.smtp.auth", "true"); // 是否需要用户认证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密
        // 获取Session实例:
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // 设置debug模式便于调试:
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        try {
            // 设置发送方地址:
            message.setFrom(new InternetAddress("1318523317@qq.com"));
            // 设置接收方地址:
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(h.get("email").toString()));
            // 设置邮件主题:
            message.setSubject("Hello", "UTF-8");
            // 设置邮件正文:
            message.setText(path, "UTF-8");
            // 发送:
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String buildToken() {

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String md5 = "";

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(uuid.getBytes("UTF-8"));
            byte[] result = md.digest();
            md5 = new BigInteger(1,result).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return md5;
    }

    @Override
    public HashMap getReport(UserLoginBean userLoginBean) {

        emailSend(userLoginBean);
        hm.put("status","1");
        hm.put("msg","发送成功");

        return hm;
    }

}